package com.shop.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.admin.dao.OrganizationDao;
import com.shop.admin.dao.ShopAdminDao;
import com.shop.admin.dao.ShopIndentDao;
import com.shop.admin.entity.Organization;
import com.shop.admin.entity.ShopAdmin;
import com.shop.admin.entity.ShopIndent;
import com.shop.admin.service.OrganizationService;
import com.shop.admin.service.ShopAdminService;
import com.shop.admin.service.ShopIndentService;
import com.shop.admin.service.ShopUserService;
import com.shop.admin.utils.CollectorsUtils;
import com.shop.admin.utils.PageUtils;
import com.shop.admin.utils.Query;
import com.shop.admin.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.events.Event;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class OrganizationServiceImpl extends ServiceImpl<OrganizationDao, Organization> implements OrganizationService {

    @Resource
    private ShopAdminDao shopAdminDao;

    @Resource
    private ShopIndentDao shopIndentDao;

    @Resource
    private OrganizationService organizationService;

    @Resource
    private ShopIndentService shopIndentService;

    @Resource
    private ShopUserService userService;

    @Resource
    private ShopIndentService indentService;

    @Override
    public PageUtils schoolList(Map<String, Object> params) {
        IPage<Organization> page = this.page(
                new Query<Organization>().getPage(params),
                new QueryWrapper<Organization>().lambda().eq(Organization::getFatherId,0)
        );
        return new PageUtils(page);
    }

    @Override
    public List<AdminMapVo> sonSchoolList1(Map<String, Object> params) {
        List<Organization> schoolList = organizationService.list(new QueryWrapper<Organization>().lambda().eq(Organization::getFatherId, 0));
        List<Integer> integers = schoolList.stream().map(i -> i.getId()).collect(Collectors.toList());
        List<Organization> organizations = organizationService.list(new QueryWrapper<Organization>().lambda().in(Organization::getFatherId,integers));
        List<AdminMapVo> adminMapVos = schoolList.stream().map(item -> {
            AdminMapVo adminMapVo = new AdminMapVo();
            adminMapVo.setId(item.getId());
            adminMapVo.setSchoolName(item.getOrgName());
            List<Integer> integerList = organizationService.list(new LambdaQueryWrapper<Organization>().eq(Organization::getFatherId, item.getId())).stream().map(i -> i.getId()).collect(Collectors.toList());
            DataVo dataVo = shopIndentDao.getSchoolDataCount(integerList);
            Integer count =userService.count();
            long num = indentService.list(new QueryWrapper<ShopIndent>().lambda()
                    .select(ShopIndent::getUserId)
            ).stream().distinct().count();
            dataVo.setNum(num);
            dataVo.setUserCount(count);
            adminMapVo.setDataVo(dataVo);
            List<IzationVo> datas = shopIndentDao.getSchoolDataIzation(integerList);
            List<Object> days = datas.stream().map(IzationVo::getDate).collect(Collectors.toList());
            List<Object> decimals = datas.stream().map(IzationVo::getTotal).collect(Collectors.toList());
            List<Object> profit = datas.stream().map(IzationVo::getProfit).collect(Collectors.toList());
            List<Object> counts = datas.stream().map(IzationVo::getStrokeCount).collect(Collectors.toList());
            Map<String, List<Object>> map=new HashMap<>();
            map.put("日期",days);
            map.put("销售额",decimals);
            map.put("利润额",profit);
            map.put("销售量",counts);
            adminMapVo.setSchoolMap(map);
            return adminMapVo;
        }).collect(Collectors.toList());
        List<AdminMapVo> mapVos = adminMapVos.stream().distinct().map(item -> {
            AdminMapVo adminMapVo = new AdminMapVo();
            BeanUtils.copyProperties(item, adminMapVo);
//                List<MapVo> mapVoList = new ArrayList<>();
//            for (Organization organization : organizations) {
//                if (organization.getFatherId().equals(item.getId())){
//                    MapVo mapVo = new MapVo();
//                    mapVo.setId(organization.getId());
//                    mapVo.setOrgName(organization.getOrgName());
//                    mapVoList.add(mapVo);
//            }
//            }
            List<Organization> list = organizationService.list(new QueryWrapper<Organization>().lambda().eq(Organization::getFatherId, item.getId() ));
            adminMapVo.setOrganizationList(list);
            return adminMapVo;
        }).collect(Collectors.toList());

        return mapVos;
    }

    @Override
    public List<OrganizationAdminCountVo> getOrganizationAdminCount(DataAdminVo vo) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        //今日
        String format01 = simpleDateFormat.format(date);

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        Date time = calendar.getTime();
        //昨日
        String format02 = simpleDateFormat.format(time);

        List<ShopAdmin> shopAdmins = shopAdminDao.selectList(new QueryWrapper<ShopAdmin>().lambda().select(ShopAdmin::getId, ShopAdmin::getAdminName, ShopAdmin::getReceiveEmail, ShopAdmin::getOrgId));
        List<Long> ids = shopAdminDao.selectList(new QueryWrapper<ShopAdmin>().lambda().eq(ShopAdmin::getOrgId,vo.getOrgId()).eq(ShopAdmin::getStatus, 1)).stream().map(i -> i.getId()).collect(Collectors.toList());
        List<OrganizationAdminCountVo> collect =ids.stream().map(item -> {
            OrganizationAdminCountVo organizationAdminCountVo = new OrganizationAdminCountVo();
            organizationAdminCountVo.setOrgId(vo.getOrgId());
            organizationAdminCountVo.setId(item.intValue());
            shopAdmins.forEach(admin -> {
                if (admin.getId().equals(item.longValue())) {
                    organizationAdminCountVo.setAdminName(admin.getAdminName());
                    organizationAdminCountVo.setReceiveEmail(admin.getReceiveEmail());
                }
            });
            Integer numDay = shopIndentDao.selectCount(new QueryWrapper<ShopIndent>()
                    .lambda().eq(ShopIndent::getIndentStatus, 3)
                    .eq(ShopIndent::getAdminId, item)
                    .like(ShopIndent::getCreateTime, format01));
            organizationAdminCountVo.setNumDay(numDay);

            Integer numYester = shopIndentDao.selectCount(new QueryWrapper<ShopIndent>()
                    .lambda().eq(ShopIndent::getIndentStatus, 3)
                    .eq(ShopIndent::getAdminId, item)
                    .like(ShopIndent::getCreateTime, format02));
            organizationAdminCountVo.setNumYesterDay(numYester);

            Integer selectCount = shopIndentDao.selectCount(new QueryWrapper<ShopIndent>()
                    .lambda().eq(ShopIndent::getIndentStatus, 3)
                    .eq(ShopIndent::getAdminId, item));
            organizationAdminCountVo.setNumCount(selectCount);
            return organizationAdminCountVo;
        }).collect(Collectors.toList());
        //今日
        List<ShopIndent> shopIndents1 = shopIndentService.list(new QueryWrapper<ShopIndent>().lambda().like(ShopIndent::getCreateTime, format01).eq(ShopIndent::getIndentStatus, 3).eq(ShopIndent::getOrgId,vo.getOrgId()));
        long count1 = shopIndents1.stream().count();
        int size = collect.size();
        long l1 = count1 / size;//今日平均单数
        //昨日
        List<ShopIndent> shopIndents2 = shopIndentService.list(new QueryWrapper<ShopIndent>().lambda().like(ShopIndent::getCreateTime, format02).eq(ShopIndent::getIndentStatus, 3).eq(ShopIndent::getOrgId,vo.getOrgId()));
        long count2 = shopIndents2.stream().count();
        long l2 = count2 / size;//昨日平均单数
        BigDecimal bigDecimal1 = shopIndents1.stream().collect(CollectorsUtils.summingBigDecimal(ShopIndent::getPrices));
        if (bigDecimal1==null) {bigDecimal1=new BigDecimal(0);}
        BigDecimal bigDecimal2 = shopIndents2.stream().collect(CollectorsUtils.summingBigDecimal(ShopIndent::getPrices));
        if (bigDecimal2==null) {bigDecimal2=new BigDecimal(0);}
        BigDecimal divide1 = bigDecimal1.divide(new BigDecimal(collect.size()),BigDecimal.ROUND_CEILING);//今日平均值
        BigDecimal divide2 = bigDecimal2.divide(new BigDecimal(collect.size()),BigDecimal.ROUND_CEILING);//昨日平均值
        for (OrganizationAdminCountVo organizationAdminCountVo : collect) {
            long l3 = organizationAdminCountVo.getNumDay().longValue() - l1;
            organizationAdminCountVo.setNumDayMarry(divide1.add(new BigDecimal(l3).multiply(new BigDecimal(1.5))));
            long l4 = organizationAdminCountVo.getNumYesterDay().longValue() - l2;
            organizationAdminCountVo.setNumYesterDayMarry(divide2.add(new BigDecimal(l4).multiply(new BigDecimal(1.5))));
        }
        return collect;
    }

    @Override
    public boolean selectBoolean(Integer id,String orgName, Integer fatherId) {
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Organization::getOrgName, orgName).eq(Organization::getFatherId,fatherId)
                .ne(id != null, Organization::getId, id);
        int count = this.baseMapper.selectCount(queryWrapper);
        return count == 0;
    }

}
